<script setup lang="ts">
import SelectUserPage from './selectUser.vue'
import { onBeforeRouteLeave } from "vue-router";
import { allocatedUserListApi, authUserCancelAllApi, getRoleApi } from "@/api/system/role";

const { sys_normal_disable } = useDict("sys_normal_disable")

const { proxy } = getCurrentInstance();

const route = useRoute();

const router = useRouter();

// 角色用户搜索框
const queryUserRef = ref();

// 遮罩层
const loading = ref(false);

// 选中数组
const selection = ref<UserRecord[]>([])

// 非单个禁用
const single = ref(true);

// 非多个禁用
const multiple = ref(true);

// 角色详情
const roleInfo = ref<RoleRecord>({});

// 用户表数据
const userList = ref<UserRecord[]>([]);

// 弹出层标题
const title = ref("");

// 编辑弹出层
const openEdit = ref(false);

//总条数
const total = ref(0);

// 列信息
const columns = ref<TableColumnsRecord>({
  colNo: { label: "序号", visible: true },
  userName: { label: "用户名称", visible: true },
  nickName: { label: "用户昵称", visible: true },
  email: { label: "邮箱", visible: true },
  phonenumber: { label: "手机", visible: true },
  status: { label: "状态", visible: true },
  createTime: { label: "创建时间", visible: true },
  userDescribe: { label: "描述", visible: true },
})

// 查询参数
const queryParams = ref<RoleAuthRecord>({
  pageNum: 1,
  pageSize: 10,
  roleId: route.params.roleId,
  userName: null,
  phonenumber: null,
});

/** 获取角色详情 */
function getRoleData() {
  getRoleApi(route.params.roleId).then(response => {
    roleInfo.value = response.data;
  })
}

/** 查询用户列表 */
function getList() {
  loading.value = true;
  allocatedUserListApi(queryParams.value).then(response => {
    userList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    userList.value.forEach((item, index) => {
      item['colNo'] = sequenceNo(index, queryParams.value);
    })
  });
}

/** 关闭弹窗 */
function closeDialog(refresh: boolean) {
  if (refresh) {
    getList();
  }
  openEdit.value = false;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryUserRef.value.resetFields()
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selectionList: UserRecord[]) {
  selection.value = selectionList;
  single.value = selectionList.length !== 1;
  multiple.value = !selectionList.length;
}

/** 新增按钮操作 */
function handleAdd() {
  openEdit.value = true;
  title.value = "选择用户";
}

/** 删除按钮操作 */
function handleDelete(row: UserRecord | any) {
  let ids = [];
  if (row.userId) {
    ids = [row.userId];
  } else {
    ids = selection.value.map(item => item.userId);
  }
  // @ts-ignore
  proxy.$modal.confirm(row.userId ? `确认要取消用户"${row.userName}""${roleInfo.value.roleName}"角色授权吗？` :
          `是否取消选中用户"${roleInfo.value.roleName}"角色授权吗`,
      "系统提示", {
        type: "warning",
      }).then(() => {
    return authUserCancelAllApi({
      roleId: roleInfo.value.roleId,
      userIds: ids.join(','),
    });
  }).then(() => {
    getList();
    // @ts-ignore
    proxy.$modal.msgSuccess("取消授权成功");
  }).catch(() => {
  });
}

/** 返回 */
function handleBack() {
  router.back();
}

onBeforeRouteLeave(() => {
  useTagsViewStore().delView(<RouterRecord>route);
})

getRoleData();
getList();
</script>

<template>
  <div class="app-container">
    <div class="back-item">
      <el-form :model="queryParams" ref="queryUserRef" :inline="true" label-width="68px">
        <el-form-item label="角色名称" prop="roleName">
          {{ roleInfo.roleName }}
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input
              v-model="queryParams.userName"
              placeholder="请输入用户名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input
              v-model="queryParams.phonenumber"
              placeholder="请输入手机号码"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item class="item-search">
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="back-item">
      <div class="table-top mb8">
        <div class="title title-left">
          角色用户列表
        </div>
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-has-permi="['system:role:add']"
        >添加用户
        </el-button>
        <el-button
            type="danger"
            plain
            icon="CircleClose"
            :disabled="multiple"
            @click="handleDelete"
            v-has-permi="['system:role:remove']"
        >批量取消授权
        </el-button>
        <el-button
            type="warning"
            plain
            icon="Back"
            @click="handleBack"
        >返回
        </el-button>
        <span class="table-top-line" />
        <right-toolbar @queryTable="getList" :columns="columns" />
      </div>
      <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" width="55" prop="colNo" v-if="columns.colNo.visible" />
        <el-table-column label="用户名称" prop="userName" show-overflow-toolti v-if="columns.userName.visible" />
        <el-table-column label="用户昵称" prop="nickName" show-overflow-tooltip v-if="columns.nickName.visible" />
        <el-table-column label="邮箱" prop="email" show-overflow-tooltip v-if="columns.email.visible" min-width="140" />
        <el-table-column label="手机" prop="phonenumber" show-overflow-tooltip v-if="columns.phonenumber.visible"
                         min-width="140" />
        <el-table-column label="状态" prop="status" align="center" v-if="columns.status.visible">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180"
                         v-if="columns.createTime.visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="120">
          <template #default="scope">
            <el-button link type="primary" icon="CircleClose" @click="handleDelete(scope.row)"
                       v-hasPermi="['system:role:remove']">取消授权
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
      <div class="line-magin" />
    </div>
    <select-user-page v-if="openEdit" :title="title" @closeDialog="closeDialog" />
  </div>
</template>

<style scoped lang="scss">

</style>